package com.pjc.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 系统操作类
 * 
 * @author 王畅
 * @version 创建时间：2015-6-16 上午09:23:23
 */
public class SystemUtil {

	/**
	 * 判断是否Linux系统
	 * 
	 * @author 王畅
	 * @return
	 */
	public static boolean isLinux() {
		String systemName = System.getProperty("os.name");
		if (systemName != null && systemName.toLowerCase().indexOf("linux") != -1) {
			return true;
		}
		return false;
	}

	public static String getJarAbsolutePath(Class<?> cla) {
		String path = null;
		try {
			path = URLDecoder.decode(cla.getProtectionDomain().getCodeSource().getLocation().getFile(), "utf-8");
			File file = new File(path);
			path = file.getAbsolutePath();

		} catch (UnsupportedEncodingException e) {

		}
		return path;
	}

	public static String getJarAbsolutePath() {
		String path = null;
		try {
			path = URLDecoder.decode(SystemUtil.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "utf-8");
			File file = new File(path);
			path = file.getAbsolutePath();

		} catch (UnsupportedEncodingException e) {

		}
		return path;
	}

	public static String getJarPath(Class<?> cla) {
		String path = null;
		try {
			path = URLDecoder.decode(cla.getProtectionDomain().getCodeSource().getLocation().getFile(), "utf-8");
			if (path.contains(".jar")) {
				path = path.substring(0, path.lastIndexOf("/") + 1);
			}

		} catch (UnsupportedEncodingException e) {

		}
		return path;
	}

	/**
	 * 根据文件获取配置文件路径
	 * 
	 * @author 王畅
	 * @param cla
	 * @param configFile
	 * @return
	 */
	public static String GetConfigPath(Class<?> cla, String configFile) {
		String path = null;
		String real = "";
		try {
			real = URLDecoder.decode(cla.getProtectionDomain().getCodeSource().getLocation().getFile(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if (isLinux()) {
			if (real != null && real.indexOf(".jar") != 1) {
				String jarPath = getJarAbsolutePath(cla);
				path = jarPath.substring(0, jarPath.lastIndexOf("/") + 1) + "config/" + configFile;
			} else
				path = cla.getClassLoader().getResource(configFile).getPath();
		} else {
			if (real != null && real.indexOf(".jar") != 1) {
				path = getJarPath(cla) + "/" + configFile;
			} else
				path = cla.getClassLoader().getResource(configFile).getPath();
		}
		return path;
	}
}
